package model;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
import java.sql.*;

public class DBFacade {
	private String dburl = "";
	private String dbuser = "";
	private String dbpass = "";
	
	public void setDbUrl(String url) {
		dburl = url;
	}
	
	public  String getDbUrl() {
		return dburl;
	}
	
	public void setDbUser(String user) {
		dbuser = user;
	}
	
	public  String getDbUser() {
		return dbuser;
	}
	
	public void setDbPass(String pass) {
		dbpass = pass;
	}
	
	public  String getDbPass () {
		return dbpass;
	}
	
	/**
	 * Function for opening connection to the database
	 */
	public  Connection getConnection() {
		
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(getDbUrl(),getDbUser(),getDbPass());			
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	
	/*
	 * print Movie Title to Screen.
	 * and return to Manager about Movie Information
	 */
	public ArrayList<String> getRank (String longitude, String latitude) throws IOException, SQLException{
		Connection con = getConnection();
		ArrayList<String> data = new ArrayList<String>();
		ArrayList<String> result = new ArrayList<String>();
		try{
			
			Statement st = con.createStatement();
			
			ResultSet rs = st.executeQuery("SELECT word FROM word WHERE longitude <= "+( Double.parseDouble(longitude)+ 0.7 )+" and longitude >= "+(Double.parseDouble(longitude)-0.7)+" and latitude <=  "+(Double.parseDouble(latitude)+0.7)+" and latitude >= "+(Double.parseDouble(latitude)-0.7)+" ORDER BY no DESC LIMIT 15000");
			
			while(rs.next()){
				if(rs.getString(1).length() != 1)
					data.add(rs.getString("word"));
			}
			
			MapReduce mr = new MapReduce();
			mr.inputData(data);
			result = mr.getResult();
		}finally{
			con.close();
		}
		
		return result;
	}
}
